#!/usr/bin/evn python
#-*- encoding: utf-8 -*-

from fdfs_client.client import Fdfs_client
import MySQLdb
import datetime
import sys
import urllib
import urllib2

class SwitchMedia():
    
    HOST_MAIN_STR = "http://192.168.5.10/"
    DMEDIA_MAIN_STR = "http://static.dingtalk.com/media/"
    
    PATH_TMP_STR = "/home/fanglin/ROOT/tmp/"
    
    URL_DOWNLOAD_IMAGE_STR = "http://192.168.5.10/downloadDDImage.do?imageName=%s&uploadType=%d&mm=%s&dd=%s"
        
    SQL_SELECT_MEDIA_STR = "select * from %s where type = 1 limit %d"
    SQL_UPDATE_MEDIA_STR = "update %s set drawingUrl = '%s', type = 0 where cdid = %s"
    
    SQL_COUNT_MEDIA_STR = "select count(*) from %s where type = 1"
    
    FDFS_CONFIG_FILE_STR = 'client.conf'
#    FDFS_CONFIG_FILE_STR = '/home/fanglin/cronbin/client.conf'
    
    def __init__(self, host='', username='', password='', database='', charset='utf8', mm=None, dd=None):
        
        self.host = host
        self.username = username
        self.password = password
        self.database = database
        self.charset = charset
        
        self.dbconn = None
        self.cursor = None
        
        self.client = Fdfs_client(self.FDFS_CONFIG_FILE_STR)
        
        self.limit = 2000
        self.ci = 0
        self.mm = mm
        self.dd = dd

    def openDBConnect(self):
        self.dbconn = MySQLdb.connect(self.host, self.username, self.password, self.database, charset=self.charset)
    
    def closeDBConnect(self):
        
        if self.dbconn:
            self.dbconn.close()
            self.dbconn = None
        
    def getDBCursor(self):
        
        if not self.dbconn:
            self.openDBConnect()
            
        self.cursor = self.dbconn.cursor()
        
    def commit(self):
        self.dbconn and self.dbconn.commit()
        
    def rollback(self):
        self.dbconn and self.dbconn.rollback()
        
    def get(self, url):
        req = urllib2.Request(url)
        return urllib2.urlopen(req).read()
    
    def post(self, url, args):
        req = urllib2.Request(url = url, data = urllib.urlencode(args))
        return urllib2.urlopen(req).read()
    
    def count(self):
        
        if self.ci > 50:
            self.ci = 0
            self.commit()
            
        self.ci += 1
        
    def getMM(self):
        return self.mm and self.mm or datetime.datetime.now().strftime('%m')
    
    def getDD(self):
        return self.dd and self.dd or datetime.datetime.now().strftime('%d')
    
    def constructiondrawing(self):
        
        self.getDBCursor()
        
        self.cursor.execute("select * from construction.constructiondrawing where type = 1 limit %d" % (self.limit))
        
        _infos = self.cursor.fetchall()
        
        for i in _infos:
            
            filename = i[3]
            url = "%s%s" % (self.DMEDIA_MAIN_STR, filename)
            postfix = filename.split(".")[1]

            try:
                res = self.client.upload_by_buffer(urllib2.urlopen(url).read(), postfix)
            except Exception:
                continue
            
            if res.get('Status').index("success") != -1:
                
                path = res.get("Remote file_id").replace('\\', '\/')
                
#                print "update construction.constructiondrawing set drawingUrl = '%s', type = 0 where cdid = %s" % (path, i[0])
                
                self.cursor.execute("update construction.constructiondrawing set drawingUrl = '%s', type = 0 where cdid = %s" % (path, i[0]))
            
                self.count()
                
        self.commit()
        self.closeDBConnect()
                
    def phonecall(self):
        
        self.getDBCursor()
        
        self.cursor.execute("select pcid, recordUrl from information.phonecall where recordType = 2 limit %d" % (self.limit))
        
        _infos = self.cursor.fetchall()
        
        for i in _infos:
            
            url = i[1]
            postfix = "mp3"
            
#            print url

            try:
                res = self.client.upload_by_buffer(urllib2.urlopen(url).read(), postfix)
                
#                print res
                
                if res.get('Status').index("success") != -1:
                
                    path = res.get("Remote file_id").replace('\\', '\/')
                    
#                    print "update information.phonecall set recordUrl = '%s', recordType = 0 where pcid = %s" % (path, i[0])
                    
                    self.cursor.execute("update information.phonecall set recordUrl = '%s', recordType = 1 where pcid = %s" % (path, i[0]))
                
                else:
                    self.cursor.execute("update information.phonecall set recordType = 3 where pcid = %s" % (i[0]))
                
                self.count()
            except Exception:
                self.cursor.execute("update information.phonecall set recordType = 3 where pcid = %s" % (i[0]))
                
                self.count()
            
        self.commit()
        self.closeDBConnect()
                
    def counts(self, table):
        
        self.getDBCursor()
        
        self.cursor.execute(self.SQL_COUNT_MEDIA_STR % (table))
        
        _infos = self.cursor.fetchall()
        
        for i in _infos:
            print i
        
        self.closeDBConnect()
        
if __name__ == "__main__":
    
    switchMedia = SwitchMedia('192.168.5.21', 'root', 'root', 'construction', 'utf8')

    action = sys.argv[1]
    
    if action == 'switch':
        _ = sys.argv[2]
        
        if getattr(switchMedia, _):
            getattr(switchMedia, _)()
    elif action == "count":
        _ = sys.argv[2]
        
        switchMedia.counts(_)
    else:
        print "No available method"
    
#    switchMedia = SwitchMedia('192.168.5.21', 'root', 'root', 'construction', 'utf8')
    
#    switchMedia.switch()
#    switchMedia.counts()
#    switchMedia.change()

#    switchMedia.phonecall(10)